<?php
if( !defined('IN_INDEX') )
{
	printError("ACCESS DENIED", "This page is hidden.");
	exit;
}

$MONTHS = array(
	'january',
	'february',
	'march',
	'april',
	'may',
	'june',
	'july',
	'august',
	'september',
	'october',
	'november',
	'december'
);
/*
$dbhost = "localhost";
$dbuser = "walgermo";
$dbpasswd = "volospau";
$dbname = "walgermo_workoutplace";
*/
include('inc/functions_index.php');
include('inc/functions_menu.php');
include('inc/functions_user.php');
include('inc/functions_lang.php');
include('inc/functions_pm.php');

$DEFAULT_DATE_FORMAT = "d.m.Y @ H:i:s";

$TIME_ZONES = array(
	array('gmt' => -12.00, 'timezone' => 'Pacific/Kwajalein', 'text' => 'Eniwetok, Kwajalein'),
	array('gmt' => -11.00, 'timezone' => 'Pacific/Apia', 'text' => 'Midway Island, Samoa'),
	array('gmt' => -10.00, 'timezone' => 'Pacific/Honolulu', 'text' => 'Hawaii'),
	array('gmt' => -9.00, 'timezone' => 'America/Anchorage', 'text' => 'Alaska'),
	array('gmt' => -8.00, 'timezone' => 'America/Los_Angeles', 'text' => 'Pacific Time (US &amp; Canada)'),
	array('gmt' => -7.00, 'timezone' => 'America/Denver', 'text' => 'Mountain Time (US &amp; Canada)'),
	array('gmt' => -6.00, 'timezone' => 'America/Chicago', 'text' => 'Central Time (US &amp; Canada), Mexico City'),
	array('gmt' => -5.00, 'timezone' => 'America/New_York', 'text' => 'Eastern Time (US &amp; Canada), Bogota, Lima'),
	array('gmt' => -4.00, 'timezone' => 'America/Halifax', 'text' => 'Atlantic Time (Canada), Caracas, La Paz'),
	array('gmt' => -3.50, 'timezone' => 'America/St_Johns', 'text' => 'Newfoundland'),
	array('gmt' => -3.00, 'timezone' => 'America/Godthab', 'text' => 'Brazil, Buenos Aires, Georgetown'),
	array('gmt' => -2.00, 'timezone' => 'America/Noronha', 'text' => 'Mid-Atlantic'),
	array('gmt' => -1.00, 'timezone' => 'Atlantic/Azores', 'text' => 'Azores, Cape Verde Islands'),
	array('gmt' => 0.00, 'timezone' => 'Europe/London', 'text' => 'Western Europe Time, London, Lisbon, Casablanca'),
	array('gmt' => 1.00, 'timezone' => 'Europe/Berlin', 'text' => 'Brussels, Copenhagen, Madrid, Paris'),
	array('gmt' => 2.00, 'timezone' => 'Europe/Istanbul', 'text' => 'Kaliningrad, South Africa'),
	array('gmt' => 3.00, 'timezone' => 'Europe/Moscow', 'text' => 'Baghdad, Riyadh, Moscow, St. Petersburg'),
	array('gmt' => 3.50, 'timezone' => 'Asia/Tehran', 'text' => 'Tehran'),
	array('gmt' => 4.00, 'timezone' => 'Asia/Muscat', 'text' => 'Abu Dhabi, Muscat, Baku, Tbilisi'),
	array('gmt' => 4.50, 'timezone' => 'Asia/Kabul', 'text' => 'Kabul'),
	array('gmt' => 5.00, 'timezone' => 'Asia/Karachi', 'text' => 'Ekaterinburg, Islamabad, Karachi, Tashkent'),
	array('gmt' => 5.50, 'timezone' => 'Asia/Calcutta', 'text' => 'Bombay, Calcutta, Madras, New Delhi'),
	array('gmt' => 5.75, 'timezone' => 'Asia/Katmandu', 'text' => 'Kathmandu'),
	array('gmt' => 6.00, 'timezone' => 'Asia/Colombo', 'text' => 'Almaty, Dhaka, Colombo'),
	array('gmt' => 7.00, 'timezone' => 'Asia/Bangkok', 'text' => 'Bangkok, Hanoi, Jakarta'),
	array('gmt' => 8.00, 'timezone' => 'Asia/Hong_Kong', 'text' => 'Beijing, Perth, Singapore, Hong Kong'),
	array('gmt' => 9.00, 'timezone' => 'Asia/Tokyo', 'text' => 'Tokyo, Seoul, Osaka, Sapporo, Yakutsk'),
	array('gmt' => 9.50, 'timezone' => 'Australia/Darwin', 'text' => 'Adelaide, Darwin'),
	array('gmt' => 10.00, 'timezone' => 'Australia/Sydney', 'text' => 'Eastern Australia, Guam, Vladivostok'),
	array('gmt' => 11.00, 'timezone' => 'Asia/Magadan', 'text' => 'Magadan, Solomon Islands, New Caledonia'),
	array('gmt' => 12.00, 'timezone' => 'Pacific/Fiji', 'text' => 'Auckland, Wellington, Fiji, Kamchatka'),
);

function getLangList($cmd)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM lang " . $cmd;
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'iso' => $row['lang_iso'],
				'name' => $row['lang_name'],
				'local_name' => $row['lang_local_name']
			);
		}
	}
	
	return $array;
}

function listLatestWorkouts($nrToShow)
{
	global $db;
	global $CONFIG;
	$array = array();
	
	$sql = "SELECT * FROM training ORDER BY training_id DESC LIMIT 0 , " .  $nrToShow . "";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'training_id' => $row['training_id'],
				'user_id' => $row['user_id'],
				'title' => $row['title'],
				'date' => $row['date'],
				'comment' => $row['comment'],
				'bodyweight' => $row['bodyweight'],
				'timespent_hours' => $row['timespent_hours'],
				'timespent_minutes' => $row['timespent_minutes']
				);
		}
	}
	return $array;
}

function listFriendsWorkouts($nrToShow){
	$array_friends = fetch_friends($_SESSION['user_id']);
	$array_friends_id = array();
	foreach($array_friends as $friend){
		$array_friends_id[] = $friend['user_id'];
	}
	
	global $db;
	global $CONFIG;
	$array = array();
	if(!empty($array_friends_id)){
		$list_friends_id = implode(',', $array_friends_id);
		
		$sql = "SELECT * FROM training WHERE user_id IN($list_friends_id) ORDER BY training_id DESC LIMIT 0 , " .  $nrToShow . "";
		if(!$result = $db->sql_query($sql))
		{
			printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
		}
		else
		{
			while($row = $db->sql_fetchrow($result))
			{
				$array[] = array(
					'training_id' => $row['training_id'],
					'user_id' => $row['user_id'],
					'title' => $row['title'],
					'date' => $row['date'],
					'comment' => $row['comment'],
					'bodyweight' => $row['bodyweight'],
					'timespent_hours' => $row['timespent_hours'],
					'timespent_minutes' => $row['timespent_minutes']
					);
			}
		}
	}
	return $array;
}

function listFollowingWorkouts($nrToShow){
	$MY_PROFILE = new User('id',$_SESSION['user_id']);
	$my_listUser_follow = $MY_PROFILE->getUserFollowList(); 
	
	global $db;
	global $CONFIG;
	$array = array();
	if($my_listUser_follow != ''){
		$sql = "SELECT * FROM training WHERE user_id IN($my_listUser_follow) ORDER BY training_id DESC LIMIT 0 , " .  $nrToShow . "";
		if(!$result = $db->sql_query($sql))
		{
			printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
		}
		else
		{
			while($row = $db->sql_fetchrow($result))
			{
				$array[] = array(
					'training_id' => $row['training_id'],
					'user_id' => $row['user_id'],
					'title' => $row['title'],
					'date' => $row['date'],
					'comment' => $row['comment'],
					'bodyweight' => $row['bodyweight'],
					'timespent_hours' => $row['timespent_hours'],
					'timespent_minutes' => $row['timespent_minutes']
					);
			}
		}
	}
	return $array;
}

function showRandomWorkout()
{
	global $db;
	global $CONFIG;
	$array = array();
	
	$sql = "SELECT * FROM `training` ORDER BY RAND() LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'training_id' => $row['training_id'],
				'user_id' => $row['user_id'],
				'title' => $row['title'],
				'date' => $row['date'],
				'comment' => $row['comment'],
				'bodyweight' => $row['bodyweight'],
				'timespent_hours' => $row['timespent_hours'],
				'timespent_minutes' => $row['timespent_minutes']
				);
		}
	}
	return $array;

}

function formatDate($input, $dateformat)
{
	global $CONFIG;
	if($dateformat != "")
	{
		return date($dateformat, $input);
	}
	return date($CONFIG['date_format'], $input);
}

function printError($header, $text)
{
	global $db;
	global $USER;
	echo "<h1>" . $header . "</h1>\n".
	"<p>" . $text . "</p>";
	
	$header = str_replace("'", "\'", $header);
	$text = str_replace("'", "\'", $text);
	if(checkSession() && isset($USER))
	{
		$user = $USER->getId();
	}
	else
	{
		$user = 1;
	}
	$url = str_replace("'", "\'", getAddress());
	
	$sql = "INSERT INTO errors SET ".
	"error_time='" . time() . "', ".
	"error_subject='" . $header . "', ".
	"error_text='" . $text . "', ".
	"error_user='" . $user . "', ".
	"error_url='" . $url . "'";
	if(!$result = $db->sql_query($sql))
	{
		echo "<p>The error was not automatically logged.</p>";
	}
	else
	{
		echo "<p>The error has been logged an will be looked upon by admins.</p>";
	}
	
}

function getActiveUsers()
{
	global $db;
	global $CONFIG;
	
	$sql = "SELECT session_id FROM sessions WHERE session_last_visit > " . (time() - $CONFIG['session_timeout']);
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}

function ActiveUsersList($cmd)
{
	global $db;
	global $CONFIG;
	$array = array();
	
	$sql = "SELECT * FROM sessions AS t1 INNER JOIN users AS t2 ".
	"ON t1.session_user_id=t2.user_id ".
	"WHERE t1.session_last_visit > " . (time() - $CONFIG['session_timeout']);
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'user_id' => $row['user_id'],
				'session_id' => $row['session_id'],
				'firstname' => $row['user_firstname'],
				'lastname' => $row['user_lastname'],
				'country' => $row['user_country'],
				'last_visit' => $row['session_last_visit'],
				'rank' => $row['user_rank'],
				'active_page' => $row['session_page']
				);
		}
	}
	return $array;
}

function getAddress()
{
	/*** check for https ***/
	//$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
	/*** return the full address ***/
	return $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

function getVisitorIp()
{
	return $_SERVER['REMOTE_ADDR'];
}


function ucf($input)
{
	return ucfirst(strtolower($input));
}

function cryptString($input)
{
	return md5($input);
}

function subval_sort($a,$subkey) 
{
	if(count($a) > 0)
	{
		foreach($a as $k=>$v) {
			$b[$k] = strtolower($v[$subkey]);
		}
		asort($b);
		foreach($b as $key=>$val) {
			$c[] = $a[$key];
		}
		return $c;
	}
	return $a;
}

function displayPaging($total, $perPage, $url, $pageId, $tagStart, $tagEnd)
{
	$count = 1;
	$total_pages = ceil($total / $perPage);
	$break = "";

	if(isset($_REQUEST[$pageId]))
	{
		$current_page = $_REQUEST[$pageId];
	}
	else
	{
		$current_page = 1;
	}
	
	if($current_page > 1)
	{
		echo "<a href=\"" . $url . "&amp;" . $pageId . "=" . ($current_page-1) . "\">" . translate('prev_page') . "</a> | \n";
		$break = "<br />";
	}
	else
	{
		echo translate('prev_page') . " | ";
	}
	
	if($current_page < $total_pages)
	{
		echo "<a href=\"" . $url . "&amp;" . $pageId . "=" . ($current_page+1) . "\">" . translate('next_page') . "</a> \n";
		$break = "<br />";
	}
	else
	{
		echo translate('next_page') . " ";
	}
	
	echo $break;

	for($i = 1; $i<=$total_pages; $i++)
	{
		if($current_page == $i)
		{
			echo $tagStart . $i . $tagEnd . "\n";
		}
		else
		{
			echo "<a href=\"" . $url . "&amp;" . $pageId . "=" . $i . "\">" . $i . "</a>\n";
		}
		$count++;
	}
}

function getHowLongAgo($date, $display = array('year', 'month', 'day', 'hour', 'minute', 'second'), $ago = 'Ago')
{
    $date = getdate($date);
    $current = getdate();
    $p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
    $factor = array(0, 12, 30, 24, 60, 60);

    for ($i = 0; $i < 6; $i++) {
        if ($i > 0) {
            $current[$p[$i]] += $current[$p[$i - 1]] * $factor[$i];
            $date[$p[$i]] += $date[$p[$i - 1]] * $factor[$i];
        }
        if ($current[$p[$i]] - $date[$p[$i]] > 1) {
            $value = $current[$p[$i]] - $date[$p[$i]];
            return $value . ' ' . strtolower(translate($display[$i] . (($value != 1) ? 's' : ''))) . ' ' . translate($ago);
        }
    }

    return '';
}

function getHowLongAgo2($date, $dateDiff, $display = array('year', 'month', 'day', 'hour', 'minute', 'second'), $ago = 'Ago')
{
    $date = getdate($date);
    $current = getdate($dateDiff);
    $p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
    $factor = array(0, 12, 30, 24, 60, 60);

    for ($i = 0; $i < 6; $i++) {
        if ($i > 0) {
            $current[$p[$i]] += $current[$p[$i - 1]] * $factor[$i];
            $date[$p[$i]] += $date[$p[$i - 1]] * $factor[$i];
        }
        if ($current[$p[$i]] - $date[$p[$i]] > 1) {
            $value = $current[$p[$i]] - $date[$p[$i]];
            return $value . ' ' . strtolower(translate($display[$i] . (($value != 1) ? 's' : '')));
        }
    }

    return '';
}
function displayGroups()
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM groups ORDER BY groups_name ASC";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
				$array[] = array(
					'group_id' => $row['groups_id'],
					'group_name' => $row['groups_name'],
				);
		}
	}
	return $array;
}

function getGroupName($gid)
{
	global $db;
	
	$sql = "SELECT groups_name FROM groups WHERE groups_id='".$gid."' ";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
	while($row = $db->sql_fetchrow($result))
		{
			$group_name = $row['groups_name'];
		}
	}
	return $group_name;
}

function getGroupAdmin($groupname)
{
	global $db;
	
	$sql = "SELECT groups_joined_user_id FROM groups_joined WHERE groups_joined_name='".$groupname."' ";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
	while($row = $db->sql_fetchrow($result))
		{
			$admin_user_id = $row['groups_joined_user_id'];
		}
	}
	return $admin_user_id;
}

function checkIfuserIsMember($uid, $groupname)
{
	global $db;
	
	$sql = mysql_query("SELECT * FROM groups_joined WHERE groups_joined_name='". $groupname ."' AND groups_joined_user_id='".$uid."' ") or die(mysql_error());
	$num = mysql_num_rows($sql);
	if($num == 1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

function getGroupDescription($gid)
{
global $db;

	$sql = "SELECT groups_description FROM groups WHERE groups_id='".$gid."' ";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
	while($row = $db->sql_fetchrow($result))
		{
			$group_ds = $row['groups_description'];
		}
	}
	return $group_ds;

}

function getGroupPrivacy($gid)
{
	global $db;

	$sql = "SELECT groups_rank FROM groups WHERE groups_id='".$gid."' ";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
	}
	else
	{
	while($row = $db->sql_fetchrow($result))
		{
			$group_rank = $row['groups_rank'];
		}
	}
	return $group_rank;
}

function checkGroupNameExistance($input)
{
	global $db;
	
	$sql = "SELECT groups_name FROM " . GROUPS_TABLE . " WHERE groups_name='" . $input . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		if($db->sql_affectedrows() > 0)
		{
			return true;
		}
	}
	return false;
}

function smiley($msg) { 
      $msg = str_replace(":)","<img src=img/smileys/emoticon_smile.png alt=\":)\" >", $msg);
	  $msg = str_replace(":-)","<img src=img/smileys/emoticon_smile.png alt=\":)\" >", $msg);
	  $msg = str_replace("=)","<img src=img/smileys/emoticon_smile.png alt=\":)\" >", $msg);
	  $msg = str_replace("x)","<img src=img/smileys/emoticon_evilgrin.png alt=\":)\" >", $msg);
	  $msg = str_replace(":D","<img src=img/smileys/emoticon_wink.png alt=\":)\" >", $msg);
	  $msg = str_replace(";D","<img src=img/smileys/emoticon_wink.png alt=\":)\" >", $msg);
	  $msg = str_replace("=D","<img src=img/smileys/emoticon_wink.png alt=\":)\" >", $msg);
	  $msg = str_replace(":-D","<img src=img/smileys/emoticon_wink.png alt=\":)\" >", $msg);
	  $msg = str_replace(":o","<img src=img/smileys/emoticon_surprised.png alt=\":)\" >", $msg);
	  $msg = str_replace(":O","<img src=img/smileys/emoticon_surprised.png alt=\":)\" >", $msg);
	  $msg = str_replace(":-O","<img src=img/smileys/emoticon_surprised.png alt=\":)\" >", $msg);
	  $msg = str_replace(":p","<img src=img/smileys/emoticon_tongue.png alt=\":)\" >", $msg);
	  $msg = str_replace(":P","<img src=img/smileys/emoticon_tongue.png alt=\":)\" >", $msg);
	  $msg = str_replace(":-P","<img src=img/smileys/emoticon_tongue.png alt=\":)\" >", $msg);
	  $msg = str_replace(":(","<img src=img/smileys/emoticon_smile.png alt=\":)\" >", $msg);
	  $msg = str_replace(":-(","<img src=img/smileys/emoticon_smile.png alt=\":)\" >", $msg);
	  $msg = str_replace("(Y)","<img src=img/smileys/thumb_up.png alt=\":)\" >", $msg);
	  $msg = str_replace("(y)","<img src=img/smileys/thumb_up.png alt=\":)\" >", $msg);
	  $msg = str_replace("(N)","<img src=img/smileys/thumb_down.png alt=\":)\" >", $msg);
	  $msg = str_replace("(n)","<img src=img/smileys/thumb_down.png alt=\":)\" >", $msg);
      return $msg; 
} 
?>